package org.example.xls.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.xls.annotion.AutoFill;
import org.example.xls.enumeratioon.OperationType;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    /**
     * 定义切入点（拦截Mapper层方法）
     */
    @Pointcut("execution(* org.example.xls.mapper.*.*(..)) && @annotation(org.example.xls.annotion.AutoFill)")
    public void autoFillPointCut() {}

    /**
     * 前置通知：自动填充公共字段
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        OperationType operationType = signature.getMethod().getAnnotation(AutoFill.class).value();

        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) return;

        Object entity = args[0];  //约定数据存放在函数的第一个参数

        LocalDateTime localDateTime = LocalDateTime.now();

        try {
            // 设置时间字段
            if (operationType == OperationType.INSERT) {
                entity.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class).invoke(entity, localDateTime);
                entity.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class).invoke(entity,localDateTime);
            }
            else if ( operationType == OperationType.UPDATE) {
                entity.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class).invoke(entity,localDateTime);
            }
        } catch (Exception e) {
            log.error("自动填充字段失败", e);
        }
    }

}